package com.zxmr.hospital.customer.action;

import java.util.List;

import com.alibaba.fastjson.JSON;
import com.zxmr.action.Request;
import com.zxmr.action.Response;
import com.zxmr.action.ResponsePayload;
import com.zxmr.action.ResultCode;
import com.zxmr.domain.Customer;
import com.zxmr.domain.account.User;
import com.zxmr.domain.activity.Activity;
import com.zxmr.domain.activity.ActivityEntity;
import com.zxmr.domain.service.ActivityService;
import com.zxmr.domain.service.CustomerService;
import com.zxmr.hospital.customer.dto.CustomerDTO;
import com.zxmr.navigate.ExecuteException;
import com.zxmr.navigate.Executor;
import com.zxmr.util.ResourceManager;
import com.zxmr.util.UserTraceManager;
import com.zxmr.util.Utils;

public class CustomerAction extends Executor{

	enum method{
		add,
		query,
		search,
		update;
	}
	@Override
	public void execute(Request request, Response response) {
		// TODO Auto-generated method stub
		try
		{
			method method = Enum.valueOf(method.class, this.getElement().getMethod());
			switch(method)
			{
			case add:
				add(request,response);
				break;
			case update:
				update(request,response);
				break;
			case query:
				query(request,response);
				break;
			case search:
				search(request,response);
			}

		}catch(Exception e)
		{
			ResponsePayload payload = new ResponsePayload();
			if(e instanceof ExecuteException)
			{
				payload.setValue(e.getMessage());
			}else
			{
				e.printStackTrace();
				payload.setValue("internal error");
			}
			response.setPayload(payload);
			response.setResult(ResultCode.COMPONENT_ERROR);
		}

	}

	private void search(Request request,Response response)throws ExecuteException
	{
		String value = request.getRequestParameters().get("value");
		
		CustomerService service = new CustomerService();
		List<Customer> customers = service.search(value, request.getAccount().getCompany());
		
		ResponsePayload payload = new ResponsePayload(JSON.toJSONString(customers));
		response.setPayload(payload);
	}
	private void query(Request request,Response response)throws ExecuteException
	{
		int id = parseId(request);
		CustomerService service = new CustomerService();
		Customer customer = service.queryCustomer(id);
		if(customer.getCompany()!= request.getAccount().getCompany())
				throw new ExecuteException(ResourceManager.getInstance().getMessage("com.zxmr.customer.noauth"));
		
		CustomerDTO dto = convertCustomerToDTO(customer);
		ResponsePayload payload = new ResponsePayload(JSON.toJSONString(dto));
		response.setPayload(payload);
	}
	private int parseId(Request request)throws ExecuteException
	{
		String id = request.getRequestParameters().get("id");
		try
		{
			return Integer.parseInt(id);
		}catch(Exception e)
		{
			throw new ExecuteException(ResourceManager.getInstance().getMessage("com.zxmr.customer.errorPara"));
		}
	}
	private void add(Request request,Response response)throws ExecuteException
	{
		CustomerDTO dto = parseRequest(request);
		User user = request.getAccount();
		
		Customer customer = convertDTOToCustomer(dto,user);
		
		customer.setAddTime(Utils.getCurrentTime());
		customer.setAddUser(user.getName());
		
		CustomerService service = new CustomerService();
		int id = service.addCustomer(customer);
		if(id == -1)
		{
			internalErrorResponse(response);
		}else
		{
			customer.setId(id);
			Activity activity = new Activity();
			activity.setUser(user.getName());
			activity.setEntity(ActivityEntity.customer);
			activity.setEntityId(id);
			activity.setTime(Utils.getCurrentTime());
			activity.setContent(ResourceManager.getInstance().getMessage("com.zxmr.customer.add"));
			
			ActivityService as = new ActivityService();
			as.addActivity(activity);
			
		}
	}
	private void update(Request request,Response response)throws ExecuteException
	{
		CustomerDTO dto = parseRequest(request);
		User user = request.getAccount();
		
		Customer customer = convertDTOToCustomer(dto,user);
		authUpdate(user,customer);
		
		customer.setLastEditTime(Utils.getCurrentTime());
		customer.setLastEditUser(user.getName());
		
		CustomerService service = new CustomerService();
		if(!service.updateCustomer(customer))
		{
			internalErrorResponse(response);
		}else
		{
			String action = ResourceManager.getInstance().getMessage("com.zxmr.customer.updateCustomer", customer.getName(),String.valueOf(customer.getId()));
			UserTraceManager.addTrace(action, request.getAccount());
		}
	}
	private void authUpdate(User user,Customer customer)throws ExecuteException
	{
		CustomerService service = new CustomerService();
		Customer orign = service.queryCustomer(customer.getId());
		if(orign == null)throw new ExecuteException(ResourceManager.getInstance().getMessage("com.zxmr.customer.misCustomer"));
		if(orign.getCompany()!= user.getCompany())throw new ExecuteException(ResourceManager.getInstance().getMessage("com.zxmr.customer.noauth"));
		if(customer.getImage() == null || "".equals(customer.getImage())) {
			customer.setImage(orign.getImage());
		}
	}
	private CustomerDTO parseRequest(Request request)throws ExecuteException
	{
		try
		{
			String parameter = request.getRequestParameters().get("parameters");
			CustomerDTO dto = JSON.parseObject(parameter, CustomerDTO.class);
			return dto;
		}catch(Exception e)
		{
			throw new ExecuteException(ResourceManager.getInstance().getMessage("com.zxmr.customer.errorPara"));
		}
	}
	private Customer convertDTOToCustomer(CustomerDTO dto,User user)
	{
		Customer customer = new Customer();
		customer.setId(dto.getId());
		customer.setAge(dto.getAge());
		customer.setCell(dto.getCell());
		customer.setCity(dto.getCity());
		customer.setId(dto.getId());
		if(!Utils.isStringEmptyWithTrim(dto.getImage()))
		{
			customer.setImage(dto.getImage());
		}
		
		customer.setName(dto.getName());
		customer.setProvince(dto.getProvince());
		customer.setQq(dto.getQq());
		customer.setWeixin(dto.getWeixin());
		customer.setSex(dto.getSex());
		customer.setWork(dto.getWork());
		customer.setEmail(dto.getEmail());
		customer.setItems(dto.getItems());
		customer.setCustomerType(dto.getCustomerType());
		customer.setCompany(user.getCompany());
		
		return customer;
		
	}
	private CustomerDTO convertCustomerToDTO(Customer customer)
	{
		CustomerDTO dto = new CustomerDTO();
		dto.setId(customer.getId());
		dto.setAge(customer.getAge());
		dto.setCell(customer.getCell());
		dto.setCity(customer.getCity());
		dto.setId(customer.getId());
		dto.setImage(customer.getImage());
		dto.setName(customer.getName());
		dto.setProvince(customer.getProvince());
		dto.setQq(customer.getQq());
		dto.setWeixin(customer.getWeixin());
		dto.setSex(customer.getSex());
		dto.setWork(customer.getWork());
		dto.setEmail(customer.getEmail());
		dto.setAddUser(customer.getAddUser());
		dto.setAddTime(customer.getAddTime());
		dto.setLastEditUser(customer.getLastEditUser());
		dto.setLastEditTime(customer.getLastEditTime());
		dto.setItems(customer.getItems());
		dto.setCustomerType(customer.getCustomerType());
		return dto;
	}
}
